﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace LuckDraw.Utils
{
    public class LogHelper
    {
        private static object lockobj = new object();//文件访问枷锁
      

        /// <summary>
        /// 写入Config数据
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static bool WriteConfig(string content, string name)
        {
            try
            {
                var path = AppDomain.CurrentDomain.BaseDirectory + $"Logs\\Config";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string filepath = $"{path}\\" + name + ".txt";
                if (File.Exists(filepath))
                {
                    File.Delete(filepath);
                }
                WriteLog(content, filepath);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 读取Config数据
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string ReadConfig(string name)
        {
            try
            {
                var path = AppDomain.CurrentDomain.BaseDirectory + $"Logs\\Config";
                string filepath = $"{path}\\" + name + ".txt";
                if (!File.Exists(filepath))
                {
                    return "";
                }
                return ReadLog(filepath);
            }
            catch (Exception)
            {
                return "";
            }
        }

        private static void WriteLog(string data, string path)
        {
            lock (lockobj)
            {
                //File.WriteAllText(path, data);
                using (StreamWriter sw = new StreamWriter(path, true))
                {
                    sw.WriteLine(data);
                    //关闭文件
                    sw.Close();
                    //释放对象
                    sw.Dispose();
                }
            }
        }
        private static string ReadLog(string path)
        {
            lock (lockobj)
            {
                //return File.ReadAllText(path);
                string data = string.Empty;
                using (StreamReader sw = new StreamReader(path, true))
                {
                    data = sw.ReadToEnd();
                    //关闭文件
                    sw.Close();
                    //释放对象
                    sw.Dispose();
                    return data;
                }
            }
        }
    }
}
